<template>
  <div class="create-document">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据库文档生成器</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 在线连接模式 -->
        <el-tab-pane label="在线连接" name="connection">
          <DatabaseConnectionForm :loading="loading" @submit="handleConnectionSubmit" />
        </el-tab-pane>

        <!-- SQL文件模式 -->
        <el-tab-pane label="SQL文件" name="sqlFile">
          <SqlUploadForm :loading="loading" @submit="handleSqlSubmit" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 任务状态显示 -->
    <TaskStatus
      v-if="currentTask"
      :task="currentTask"
      class="task-status-section"
      @view-result="handleViewResult"
      @export="handleExport"
      @delete="handleDeleteTask"
    />

    <!-- 文档结果预览 -->
    <el-dialog v-model="resultVisible" title="文档预览" width="90%" fullscreen destroy-on-close>
      <div class="result-actions">
        <el-button @click="handleExport('md')">导出Markdown（推荐）</el-button>
        <el-button @click="handleExport('html')">导出HTML</el-button>
        <el-button @click="resultVisible = false">关闭</el-button>
      </div>
      <div v-if="resultHtml" class="document-preview" v-html="resultHtml"></div>
      <el-empty v-else description="暂无文档内容" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'
import DatabaseConnectionForm from '@/components/document/DatabaseConnectionForm.vue'
import SqlUploadForm from '@/components/document/SqlUploadForm.vue'
import TaskStatus from '@/components/document/TaskStatus.vue'
import { useDocumentStore } from '@/stores/document'
import { pollTaskStatus } from '@/utils/task'
import type { DatasourceConnection } from '@/types/document'

const documentStore = useDocumentStore()

const activeTab = ref('connection')
const resultVisible = ref(false)
const loading = ref(false)

const { currentTask, resultHtml } = storeToRefs(documentStore)

// 处理数据库连接提交
const handleConnectionSubmit = async (connection: DatasourceConnection) => {
  await createTask({ connection })
}

// 处理SQL文件提交
const handleSqlSubmit = async (sqlContent: string) => {
  await createTask({ sqlContent })
}

// 创建任务 - 修复这里的逻辑
const createTask = async (request: any) => {
  loading.value = true
  try {
    console.log('开始创建任务:', request)
    const task = await documentStore.createTask(request)
    console.log('任务创建成功:', task.taskId)
    ElMessage.success('任务创建成功，正在生成文档...')

    // 开始轮询任务状态 - 确保传递正确的 taskId
    await pollTaskStatus(
      task.taskId, // 这里必须是 task.taskId，不是 task.id
      documentStore.fetchTask,
      () => {
        ElMessage.success('文档生成成功！')
      },
      (error) => {
        ElMessage.error(`文档生成失败: ${error}`)
      },
    )
  } catch (error: any) {
    console.error('创建任务失败:', error)
    ElMessage.error(`创建任务失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 查看文档结果
const handleViewResult = async () => {
  if (!currentTask.value) return

  try {
    await documentStore.fetchTaskResult(currentTask.value.taskId)
    resultVisible.value = true
  } catch (error: any) {
    ElMessage.error(`获取文档失败: ${error.message}`)
  }
}

// 导出文档
const handleExport = async (format: 'html' | 'md') => {
  if (!currentTask.value) return

  try {
    await documentStore.exportDocument(currentTask.value.taskId, format)
    ElMessage.success('导出成功')
  } catch (error: any) {
    ElMessage.error(`导出失败: ${error.message}`)
  }
}

// 删除任务
const handleDeleteTask = async () => {
  if (!currentTask.value) return

  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '提示', {
      type: 'warning',
    })

    await documentStore.deleteTask(currentTask.value.taskId)
    ElMessage.success('删除成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

onMounted(() => {
  documentStore.clearState()
})
</script>

<style scoped>
.create-document {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.task-status-section {
  margin-top: 20px;
}

.result-actions {
  margin-bottom: 16px;
}

.document-preview {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background: white;
  min-height: 400px;
}
</style>
